﻿using Ekton_Manage_DomainCore;
using Ekton_Manage_DomainCore.Aggregate;
using Ekton_Manage_Framework.Redis;
using Ekton_Manage_IBusiness;
using Ekton_Manage_InfrastructureCore.Repositories;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MimeKit;
using MimeKit.Text;
using static Ekton_Manage_DTO.CommonModels.DtoFileModel;
using Ekton_Manage_InfrastructureCore.Common;

namespace Ekton_Manage_Business
{

    public class JobBusiness : IJobBusiness
    {
        private readonly IBaseRepository<msg_push, int> _baseMaterialRepository;
        private readonly IBaseRepository<user_list, int> _baseuserlistRepository;
        private readonly IBaseRepository<company_email, int> _basecompanyEmailrepository;
        private readonly IBaseRepository<msg_user, int> _basemsguserrepository;
        private readonly ApplicationDbContent _content;
        private readonly Connection _connection;
        public JobBusiness(IBaseRepository<msg_push, int> baseMaterialRepository, IBaseRepository<user_list, int> baseuserlistRepository, IBaseRepository<company_email, int> basecompanyEmailrepository, ApplicationDbContent content, IBaseRepository<msg_user, int> basemsguserrepository, Connection connection)
        {
            _baseMaterialRepository = baseMaterialRepository;
            _baseuserlistRepository = baseuserlistRepository;
            _basecompanyEmailrepository = basecompanyEmailrepository;
            _content = content;
            _basemsguserrepository = basemsguserrepository;
            _connection = connection;
        }
        public Task Run()
        {
            Console.WriteLine($"{nameof(Run)}{DateTime.Now}执行了一次！");
            return Task.CompletedTask;
        }

        public Task SecondRun()
        {
            Console.WriteLine($"{nameof(SecondRun)}{DateTime.Now}执行了一次！");
            return Task.CompletedTask;
        }

        /// <summary>
        /// 从队列里取要发送的邮件,每次五条
        /// </summary>
        /// <returns></returns>
        public Task SendEmailByQueue()
        {
            //根据平台id查询发件人的邮箱
            var companyEmail = _basecompanyEmailrepository.QuerySingleData(m => m.platform_id == 26).Result;
            var username = companyEmail.email.Split("@")[0];//用户名
            string password = companyEmail.author_code;//授权码
            for (int i = 0; i < 5; i++)
            {
                string result = _connection.db.ListRightPop("emailList");//从列表的尾部拾取消息
                if (string.IsNullOrEmpty(result)) return Task.CompletedTask;
                var emailData = JsonConvert.DeserializeObject<EmailByQueue>(result);

                //邮箱推送消息
                MailMessage mailMessage = new MailMessage();
                //发件人
                mailMessage.From = new MailAddress(companyEmail.email);
                //邮件标题
                mailMessage.Subject = emailData.subject;
                //邮件内容
                mailMessage.Body = emailData.body;
                SmtpClient client = new SmtpClient();
                client.Host = "smtp.qq.com";
                client.EnableSsl = true;
                client.UseDefaultCredentials = false;
                client.Credentials = new NetworkCredential(username, password);
                mailMessage.To.Add(new MailAddress(emailData.address));
                client.Send(mailMessage);
            }
            return Task.CompletedTask;
        }

        /// <summary>
        /// email邮箱定时推送
        /// </summary>
        /// <returns></returns>
        public async Task SendEmail()
        {
            //查出要推送的消息
            var email_push = await _baseMaterialRepository.QueryTableList(m => m.state == 0 && m.push == 1 && m.push_method == 1);
            if (email_push == null) return;//如果为空，则表示没有消息需要推送
            foreach (var item in email_push)
            {
                DateTime startTime = item.push_time;//推送时间
                DateTime endTime = DateTime.Now;//当前时间
                TimeSpan ts = startTime - endTime;//推送时间和当前时间做差
                if (startTime.CompareTo(endTime) > 0)//startTime.CompareTo(endTime) > 0
                {
                    //到了要推送的时间
                    if (item.push_user == 0)//推送给全部用户
                    {
                        var companyEmail = await _basecompanyEmailrepository.QuerySingleData(m => m.platform_id == 30);
                        if (companyEmail == null) return;
                        //查询全部用户    
                        var userInfo = await _baseuserlistRepository.QueryTableList(m => true);
                        string address = "";//收件人
                        foreach (var userItem in userInfo)
                        {
                            address += userItem.email + ",";
                        }
                        Task.Run(() =>
                        {
                            string host = "smtp.qq.com";//qq邮箱
                            int port = 465;//25 465 587
                                           //发件人的邮箱
                            string from = companyEmail.email;
                            string to = address;
                            //发件人邮箱@符前面的部分
                            var temp = companyEmail.email.Split("@")[0];
                            string userName = temp;//用户登录名
                            string password = companyEmail.author_code;//授权码

                            var message = new MimeMessage();
                            message.From.Add(new MailboxAddress(from));
                            //message.To.AddRange(new MailboxAddress[] { new MailboxAddress(to) });
                            message.Subject = item.title;
                            var entity = new TextPart(TextFormat.Html)
                            {
                                Text = item.msg_context
                            };
                            message.Body = entity;
                            MailKit.Net.Smtp.SmtpClient client = new MailKit.Net.Smtp.SmtpClient();
                            client.Connect(host, port, port == 465);//465端口是ssl端口
                            client.Authenticate(userName, password);
                            string[] email = address.Split(',');
                            foreach (string name in email)
                            {
                                if (name is null) { };
                                if (name != string.Empty)
                                {
                                    //每次发邮件前清空收件人
                                    message.To.Clear();
                                    address = name;
                                    message.To.AddRange(new MailboxAddress[] { new MailboxAddress(name) });
                                    client.Send(message);
                                }
                            }
                            client.Disconnect(true);
                            Console.WriteLine("发送邮件成功");
                        });

                    }
                    else if (item.push_user == 1)//指定用户推送
                    {
                        //查询发送邮件的发件人邮箱
                        var companyEmail = await _basecompanyEmailrepository.QuerySingleData(m => m.platform_id == 30);
                        if (companyEmail == null) return;
                        Task.Run(() =>
                        {
                            string address = item.push_user_email;
                            string host = "smtp.qq.com";//qq邮箱
                            int port = 465;//25 465 587
                            //发件人的邮箱
                            string from = companyEmail.email;
                            string to = address;
                            //发件人邮箱@符前面的部分
                            var temp = companyEmail.email.Split("@")[0];
                            string userName = temp;//用户登录名
                            string password = companyEmail.author_code;//授权码

                            var message = new MimeMessage();
                            message.From.Add(new MailboxAddress(from));
                            //message.To.AddRange(new MailboxAddress[] { new MailboxAddress(to) });
                            message.Subject = item.title;
                            var entity = new TextPart(TextFormat.Html)
                            {
                                Text = item.msg_context
                            };
                            message.Body = entity;
                            MailKit.Net.Smtp.SmtpClient client = new MailKit.Net.Smtp.SmtpClient();
                            client.Connect(host, port, port == 465);//465端口是ssl端口
                            client.Authenticate(userName, password);
                            string[] email = address.Split(',');
                            foreach (string name in email)
                            {
                                if (name is null) { };
                                if (name != string.Empty)
                                {
                                    //每次发邮件前清空收件人
                                    message.To.Clear();
                                    address = name;
                                    message.To.AddRange(new MailboxAddress[] { new MailboxAddress(name) });
                                    client.Send(message);
                                }
                            }
                            client.Disconnect(true);
                            Console.WriteLine("发送邮件成功");
                        });
                    }
                }
                else
                {
                    item.state = 1;
                    _ = await _baseMaterialRepository.UpdateSingleData(item);
                    Console.WriteLine("没有需要发送的邮件");
                }
                item.state = 1;
                await _baseMaterialRepository.UpdateSingleData(item);
            }
            GC.Collect();
        }

        /// <summary>
        /// 系统消息定时推送
        /// </summary>
        /// <returns></returns>
        public async Task SendSysMsg()
        {
            //查询系统消息中未推送的定时推送任务
            var msgpush = await _baseMaterialRepository.QueryTableList(m => m.push == 0 && m.push_method == 1 && m.state == 0);
            if (msgpush.Count == 0) return;
            foreach (var item in msgpush)
            {
                DateTime startTime = item.push_time;
                DateTime endTime = DateTime.Now;
                //如果startTime.CompareTo(endTime) > 0表示到了推送的时间
                if (startTime.CompareTo(endTime) > 0)
                {
                    //获取用户的id，全部则获取全部id，指定用户则从push_user_list中以逗号分隔出id
                    var userId = new List<msg_user>();
                    var empty = new List<msg_user>();
                    if (item.push_user == 0)//全部用户
                    {
                        var user = await _baseuserlistRepository.QueryTableList(m => true);
                        foreach (var userItem in user)
                        {
                            //获取全部用户的id
                            userId.Add(new msg_user
                            {
                                user_id = userItem.id,
                                msg_id = item.id,
                                look_state = 0
                            });
                        }

                        item.state = 1;
                        _ = await _baseMaterialRepository.UpdateSingleData(item);
                        //批量添加消息推送
                        var insertMsgUser = await _basemsguserrepository.InsertManyData(userId);
                    }
                    else if (item.push_user == 1)//指定用户
                    {
                        string[] strArray = item.push_user_list.Split(',');
                        var intArray = Array.ConvertAll(strArray, int.Parse);
                        for (int i = 0; i < intArray.Length; i++)
                        {
                            //获取指定用户的id
                            empty.Add(new msg_user
                            {
                                user_id = intArray[i],
                                msg_id = item.id,
                                look_state = 0
                            });
                        }

                        item.state = 1;
                        _ = await _baseMaterialRepository.UpdateSingleData(item);
                        //将数据添加到msg_user表中
                        var insertMsgUser = await _basemsguserrepository.InsertManyData(empty);
                    }
                    Console.WriteLine("发送系统消息成功");
                }
                else
                {
                    item.state = 1;
                    _ = await _baseMaterialRepository.UpdateSingleData(item);
                    Console.WriteLine("没有需要发送的邮件");
                }
            }
        }
    }
}
